<?php
declare (strict_types=1);

namespace app\api\controller;

use app\common\facade\Image;
use app\common\facade\WeChat;
use app\common\facade\WeChatMini;
use app\common\facade\QrCodes;
use app\common\model\Assets;
use app\common\model\Mechanism;
use app\common\model\Relation;
use app\common\model\UserCoupon;
use app\common\model\UserNotify;
use app\common\model\UserWarranty;
use app\common\tool\Result;
use think\exception\ValidateException;
use think\facade\View;
use app\common\model\User as UserModel;
use think\response\Json;

class User extends Base
{



    /**
     * post: 获取手机号
     * path: get_mobile
     * method: get_mobile
     */
    public function get_mobile()
    {
        $post = $this->request->post();
        $result = WeChatMini::getPhoneNumber($post['code']);
        $this->user->mobile = $result['phone_info']['phoneNumber'];
        $this->user->save();
        return Result::success('成功',$result['phone_info']['phoneNumber']);

    }

    /**
     * get: 个人信息
     * path: get_user
     * method: get_user
     */
    public function get_user()
    {
        $data['user'] = UserModel::where('id',$this->user->id)->field('id,nickname,code,photo,mobile')->find();
        $balance = Assets::where('uid',$this->user->id)->find();
        $data['user']['balance'] = $balance['balance'];
        $data['user']['integral'] = $balance['integral'];
        $data['user']['is_active'] = $this->user->is_active == 1 ? '普通会员' : '正式会员';
        $data['user']['level'] = $this->user->level ? $this->user->level->title : '';
        $data['user']['teamLevel'] = $this->user->teamLevel ? $this->user->teamLevel->title : '';

        if(!empty($data))
        {
            return Result::success('获取成功',$data);
        }else{
            return Result::fail('获取失败');
        }
    }


    /**
     * get: 机构说明
     * path: mechanism_details
     * method: mechanism_details
     * param: cate
     */
    public function mechanism_details(): \think\Response
    {
        $details = Mechanism::where(['id'=>$this->user->mechanism_id,'is_del'=>0,'status'=>2])->field('id,title,address,disseminate,award_information,trainees_number,teacher_number')->find();
        return Result::success('获取成功', $details);
    }

    /**
     * post: 修改信息
     * path: edit
     * method: edit
     * param: photo - {string} 头像
     * param: nickname - {string} 昵称
     * param: mechanism_id - {string} 机构id
     */
    public function edit()
    {
        try {
            $param = $this->request->post('', '', $this->filter);
            if($param['mechanism_id'])
            {
                $mechanism = Mechanism::find($param['mechanism_id']);
                $param['mechanism_uid'] = $mechanism->uid;
            }
            UserModel::update($param, ['id' => $this->user->id]);
            return json(['code' => 1, 'msg' => '已修改']);
        } catch (\Exception $e) {
            return json(['code' => -1, 'msg' => $e->getMessage()]);
        }

    }

    /**
     * get: 分享
     * path: getUserQrcode
     * method: getUserQrcode
     */
//    public function getUserQrcode(){
//        $url='/qrcode/';
//        $result = WeChatMini::getMiniScene($this->user->code,'pages/index/index', $url);
//        return Result::success('获取成功！',$result);
//    }

    public function getUserQrcode()
    {
        try {
            $url = '/qrcode/user/' . $this->user->code . '.png';
            if (!file_exists('.' . $url)) {
                $qrCodes = new QrCodes(config('pay')['wechat']);
                file_put_contents('.' . $url, $qrCodes->getMiniScenes($this->user->code,
                    'pages/register/index', 'release'));
            }
            $data = [
                'url'      => $url,
                'nickname' => $this->user->nickname,
                'code'     => $this->user->code,
                'photo'    => $this->user->photo,
            ];
            return Result::success('success', $data);
        } catch (\Exception $e) {
            return Result::fail('生成失败：' . $e->getMessage());
        }
    }


    public function wechat()
    {
//        $code = input('code');
//        $result = WeChat::getOauthAccessToken($code);
////            dump($result);die;
//        UserModel::where('id', $this->user->id)->update(['wechat_openid' => $result['openid']]);
        $user = $this->user;
        if ($user && empty($user->wechat_openid)) {
            $url = WeChat::withConfig(config('pay')['wechat_1'])->getOauthRedirect('https://' . $_SERVER['SERVER_NAME'] . '/api/index/wechat_open', $user->token);
            header("Location:" . $url);
            exit;
        }
    }

    public function wechat_open()
    {
        $token = $this->request->param('state', '');
        $code = $this->request->param('code', '');
        //创建接口实例
        $result = WeChat::withConfig(config('pay')['wechat_1'])->getOauthAccessToken($code);
        $user = UserModel::where('token', $token)->find();
        if (empty($user->wechat_openid)) {
            UserModel::where('token', $token)->update(['wechat_openid' => $result['openid']]);
        }
        exit;
    }

    /**
     * get: 我的团队
     * path: my_team
     * method: my_team
     * param:  page 页数
     */

    public function my_team()
    {
        $page = $this->request->param('page', 1);
        $map = ['uid' => $this->user->id, 'algebra' => 1];
        $date['my_team'] = Relation::getPageList($map, '*', $page, 20, false, ['fresh']);

        $dpn = Relation::where(['uid' => $this->user->id, 'algebra' => 1])->column('new_uid');
        $team = Relation::where('uid', $this->user->id)->count();

        $date['dpn'] = count($dpn);
        $date['dpn_total'] = UserModel::whereIn('id', $dpn)->sum('my_total');
        $date['team'] = $team;
        $date['team_total'] = $this->user->team_total;
        return Result::success('获取数据成功！',$date);
    }


    /**
     * get: 收款方式
     * path: method_index
     * method: method_index
     */
    public function method_index()
    {
        $mode = [
//            ['name' => '支付宝', 'type' => 'alipay'],
//            ['name' => '微信', 'type' => 'wechat'],
            ['name' => '银行卡', 'type' => 'bank']
        ];
        return Result::success('获取数据成功！',$mode);
    }


    /**
     * get: 收款方式类型
     * path: method_info
     * method: method_info
     * param:  type 类型
     */
    public function method_info()
    {
        $type=$this->request->param('type');
        switch ($type) {
            case "alipay":
            case "wechat":
                $name = $type . '_name';
                $image = $type . '_image';
                $result['name'] = $this->user->$name;
                $result['image'] = $this->user->$image;
                break;
            case "bank":
                if(!$this->user->bank_name||!$this->user->bank_open||!$this->user->bank_account_name||!$this->user->bank_number)
                {
                    return Result::fail('请完善收款信息');
                }
                $result['bank_name'] = $this->user->bank_name;
                $result['bank_open'] = $this->user->bank_open;
                $result['bank_account_name'] = $this->user->bank_account_name;
                $result['bank_number'] = $this->user->bank_number;
//                $result['bank_list'] = explode(PHP_EOL, $this->system['bank_list']);
                break;
            default:
                return Result::fail('加载失败');

        }
        return Result::success('获取数据成功！',$result);
    }


    /**
     * post: 收款方式修改
     * path: method_save
     * method: method_save
     * param:  type 类型
     * param:  name 姓名
     * param:  image 图片
     * param:  bank_name 银行名称
     * param:  bank_number 银行卡号
     * param:  bank_account_name 银行户名
     * param:  bank_open 开户行
     */
    public function method_save()
    {
        try {
            $param = $this->request->post();
            $type=$param['type'];
            $v = $type == 'bank' ? 'MethodBank' : 'MethodImg';
            try {
                $this->validate($param, $v);
            } catch (ValidateException $e) {
                return Result::fail($e->getError());
            }
            switch ($type) {
                case "bank":
                    break;
                default:
                    $param[$type . '_name'] = $param['name'];
                    $param[$type . '_image'] = $param['image'];
                    unset($param['name']);
                    unset($param['image']);
            }

            UserModel::update($param, ['id' => $this->user->id]);

            return Result::success('已保存');

        } catch (\Exception $e) {
            return Result::fail($e->getMessage());
        }
    }


}

